<script>
import Sortable from 'sortablejs'
import { cloneDeep } from 'lodash'
import { v4 } from 'uuid'

function exchange (index1, index2, arr) {
  const cloneArrary = cloneDeep(arr)

  arr[index1] = cloneArrary[index2]
  arr[index2] = cloneArrary[index1]
  return arr
}
export default {
  name: 'ZDragTale',
  props: {
    value: {
      type: Array,
      default: () => ([])
    }
  },
  computed: {
    currentValue: {
      get () {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        return this.value.sort((pre, next) => pre.sort - next.sort).map((record, index) => ({ ...record, unique: v4() }))
      },
      set (val) {
        const value = val.map((record, index) => ({ ...record, sort: index }))
        this.$emit('input', value)
      }
    }
  },

  data () {
    return {
      tableId: v4()
    }
  },
  mounted () {
    this.rowDropInit()
  },
  methods: {

    rowDropInit () {
      const wrapperRow = document.querySelector(
        `.z-drag-table-${this.tableId} .el-table__body-wrapper tbody`
      )
      Sortable.create(wrapperRow, {
        animation: 500,
        delay: 0,
        onEnd: ({ newIndex, oldIndex }) => {
          this.currentValue = exchange(newIndex, oldIndex, this.currentValue)
        }
      })
    }

  },
  render () {
    return (
      <el-table
        props={{ ...this.$attrs, rowKey: 'unique' }}
        on={this.$listeners}
        data={this.currentValue}
        class={{
          [`z-drag-table-${this.tableId}`]: true
        }}
      >
        {this.$slots.default}
      </el-table>
    )
  }
}
</script>

<style >
.z-drag-table .el-table__body-wrapper tbody tr {
  cursor: move;
}
</style>
